package com.graduation.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.graduation.ucenter.model.dto.UserDto;
import com.graduation.ucenter.model.po.User;
import com.graduation.ucenter.mapper.UserMapper;
import com.graduation.ucenter.model.dto.AuthParamsDto;
import com.graduation.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Mr.M
 * @version 1.0
 * @description 账号名密码方式
 * @date 2023/2/24 11:56
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDto execute(AuthParamsDto authParamsDto) {
        String username = authParamsDto.getUsername();
        String checkcode = authParamsDto.getCheckcode();
        String checkcodekey = authParamsDto.getCheckcodekey();
//        if (StringUtils.isEmpty(checkcode) || StringUtils.isEmpty(checkcodekey)) {
//            throw new RuntimeException("请输入的验证码");
//        }
        //todo:调用验证码服务校验验证码
        //判断用户是否存在
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername, username)
                .eq(User::getStatus, 1);
        User user = userMapper.selectOne(qw);
        if (user == null) {
            throw new RuntimeException("账号不存在");
        }
        //验证密码是否正确
        String passwordDb = user.getPassword();
        String passwordForm = authParamsDto.getPassword();
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches) {
            throw new RuntimeException("账号或密码错误");
        }
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        return userDto;
    }


}
